﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using Microsoft.Linq.Expressions;

namespace DlrBasic.Parser.Ast
{
    class LineInput : Statement
    {
        DlrBasicExpression prompt;
        VariableOrCall variable;

        public LineInput(SourceSpan span, DlrBasicExpression prompt, VariableOrCall variable)
            : base(span)
        {
            this.prompt = prompt;
            this.variable = variable;
        }

        protected internal override Expression Generate(DlrBasicGenerator generator, StateMemberGenerator stateParameter, LambdaBuilder builder)
        {
            List<Expression> inputExpressions = new List<Expression>();

            if (prompt != null)
            {
                Expression print = Utils.Call(typeof(DlrBasicHelpers).GetMethod("Print"),
                    prompt.SourceSpan, Utils.CodeContext(), 
                    Expression.ConvertHelper(prompt.Generate(generator), typeof(Object)));
                inputExpressions.Add(print);
            }

            Expression inputCall = Utils.Call(typeof(DlrBasicHelpers).GetMethod("InputLine"),
                SourceSpan, Utils.CodeContext(), Utils.Constant(false));

            Expression variableAssign = variable.GenerateAssign(
                generator, inputCall);
            inputExpressions.Add(variableAssign);

            inputExpressions.Add(base.Generate(generator, stateParameter, builder));

            return Expression.Block(inputExpressions.ToArray());
        }
    }
}
